package com.htthorizon.model.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.github.pagehelper.Page;
import com.htthorizon.common.core.domain.R;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.core.utils.file.FileTypeUtils;
import com.htthorizon.common.core.utils.file.MimeTypeUtils;
import com.htthorizon.common.security.utils.SecurityUtils;
import com.htthorizon.model.domain.ModelMeta;
import com.htthorizon.model.domain.ModelSource;
import com.htthorizon.model.response.ModelMessageVo;
import com.htthorizon.model.response.ModelSpecialityDto;
import com.htthorizon.model.service.IModelMetaService;
import com.htthorizon.model.service.IModelSourceService;
import com.htthorizon.system.api.RemoteFileService;
import com.htthorizon.system.api.domain.SysFile;
import com.htthorizon.system.api.model.LoginUser;
import com.htthorizon.system.api.model.ModelInfoReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.htthorizon.common.log.annotation.Log;
import com.htthorizon.common.log.enums.BusinessType;
import com.htthorizon.common.security.annotation.RequiresPermissions;
import com.htthorizon.model.domain.ModelInfo;
import com.htthorizon.model.service.IModelInfoService;
import com.htthorizon.common.core.web.controller.BaseController;
import com.htthorizon.common.core.web.domain.AjaxResult;
import com.htthorizon.common.core.utils.poi.ExcelUtil;
import com.htthorizon.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 模型信息Controller
 *
 * @author mark
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/model/info")
public class ModelInfoController extends BaseController
{
    @Autowired
    private IModelInfoService modelInfoService;

    @Autowired
    private IModelMetaService modelMetaService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private IModelSourceService modelSourceService;

    /**
     * 查询模型信息列表
     */
    @RequiresPermissions("model:info:list")
    @GetMapping("/list")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.QUERY)
    public AjaxResult list(ModelInfo modelInfo)
    {
//        startPage();
        AjaxResult ajax = AjaxResult.success();
        List<ModelSpecialityDto> dtoList = this.modelInfoService.selectModelInfoGroupBySpeciality(null);
        if(dtoList !=null && dtoList.size() > 0) {
            ajax.put("specialityDataInfo",dtoList);
            //设置默认专业域
            if(StringUtils.isEmpty(modelInfo.getSpecialityCode())){
                ModelSpecialityDto dto = dtoList.get(0);
                modelInfo.setSpecialityCode(dto.getSpecialityCode());
            }
            Integer page =modelInfo.getPageNum();
            Integer pageSize = modelInfo.getPageSize();
            Page<ModelMessageVo> pages = new Page<>();
            pages.setPageNum(page);
            pages.setPageSize(pageSize);
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setCode(200);

            TableDataInfo list = modelInfoService.selectModelInfoList2(modelInfo,pages,tableDataInfo);
//            list.forEach(mo->{
//                ModelSource modelSource = modelSourceService.selectModelSourceById(mo.getSourceId());
//                mo.setSourceName(modelSource.getSourceName());
//            });
            ajax.put("tableDataInfo", list);
        }
        return ajax;
    }

    /**
     * 查询模型信息列表
     */
    @GetMapping("/all")
    @RequiresPermissions("model:info:list")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.QUERY)
    public TableDataInfo all(ModelInfo modelInfo)
    {
        startPage();
        List<ModelInfo> list = modelInfoService.selectModelInfoList(modelInfo);
        list.forEach(mo->{
            ModelSource modelSource = modelSourceService.selectModelSourceById(mo.getSourceId());
            mo.setSourceName(modelSource.getSourceName());
        });
        return getDataTable(list);
    }

    @GetMapping("/innerAll")
    @Log(title = "系统管理/交叉审计", businessType = BusinessType.QUERY)
    public TableDataInfo all2(ModelInfo modelInfo)
    {
        startPage();
        List<ModelInfo> list = modelInfoService.selectModelInfoList(modelInfo);
        List<ModelInfo> collect = list.stream().filter((modelInfo1) -> {
            if (modelInfo1.getSourceId() == null) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        collect.forEach(mo->{
            try {
                ModelSource modelSource = modelSourceService.selectModelSourceById(mo.getSourceId());
                mo.setSourceName(modelSource.getSourceName());
            }catch (Exception e){

            }

        });
        return getDataTable(collect);
    }

    /**
     * 导出模型信息列表
     */
    @RequiresPermissions("model:info:download")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ModelInfo modelInfo)
    {
        List<ModelInfo> list = modelInfoService.selectModelInfoList(modelInfo);
        ExcelUtil<ModelInfo> util = new ExcelUtil<ModelInfo>(ModelInfo.class);
        util.exportExcel(response, list, "模型信息数据");
    }



    /**
     * 获取模型信息详细信息
     */
    @RequiresPermissions("model:info:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ModelInfo modelInfo = modelInfoService.selectModelInfoById(id);
        if(modelInfo == null){
            return error("查询模型为空！");
        }
            try {
                ModelSource modelSource = modelSourceService.selectModelSourceById(modelInfo.getSourceId());
                modelInfo.setSourceName(modelSource.getSourceName());
            }catch (Exception e){

            }
        AjaxResult ajaxResult = success(modelInfo);
        ModelMeta modelMeta = new ModelMeta();
        modelMeta.setModelId(modelInfo.getId());
        try{
            ajaxResult.put("modelMetaList", this.modelMetaService.selectModelMetaList(modelMeta));
        }catch (Exception e){

        }
        ajaxResult.put("modelMetaList", this.modelMetaService.selectModelMetaList(modelMeta));
        return success(ajaxResult);
    }

    /**
     * 新增模型信息
     */
    @RequiresPermissions("model:info:add")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")

    public AjaxResult add(@Valid @RequestBody ModelInfoReq modelInfo)
    {
     boolean result =   modelInfoService.checkModelInfo(modelInfo);
     if (!result&&!modelInfo.getModelStatus().equals("2")){
         throw new RuntimeException("模型名称已存在");
     }
        int success = modelInfoService.insertModelInfo(modelInfo);
//        if(success < 1){
//            return error("保存失败！");
//        }
        return success();
    }


    /**
     * 文档上传
     */
    @Log(title = "模型管理/模型档案需求文档上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
//    @RequiresPermissions("model:info:list")
    public AjaxResult upload(@RequestParam("documentfile") MultipartFile file){
        try {
            if (!file.isEmpty()) {
                String extension = FileTypeUtils.getExtension(file);
                if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION)) {
                    return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION) + "格式");
                }
                R<SysFile> fileResult = remoteFileService.upload(file);
                if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                    return error("文件服务异常，请联系管理员");
                }
                String url = fileResult.getData().getUrl();
                AjaxResult ajax = AjaxResult.success();
                ajax.put("fileUrl", url);
                return ajax;
            }
            return error("上传文档异常，请联系管理员");
        }catch (Exception e){
            return error("上传文档异常，"+e.getMessage());
        }
    }

    @Log(title = "模型管理/模型档案需求文档上传", businessType = BusinessType.INSERT)
    @PostMapping("/innerUpload")
//    @RequiresPermissions("model:info:list")
    public AjaxResult upload2(@RequestParam("documentfile") MultipartFile file){
        try {
            if (!file.isEmpty()) {
                String extension = FileTypeUtils.getExtension(file);
                if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                    return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
                }
                R<SysFile> fileResult = remoteFileService.uploa2(file);
                if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                    return error("文件服务异常，请联系管理员");
                }
                String url = fileResult.getData().getUrl();
                AjaxResult ajax = AjaxResult.success();
                ajax.put("fileUrl", url);
                return ajax;
            }
            return error("上传文档异常，请联系管理员");
        }catch (Exception e){
            return error("上传文档异常，"+e.getMessage());
        }
    }

    /**
     * 修改模型信息
     */
    @RequiresPermissions("model:info:edit")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody ModelInfoReq modelInfo)
    {
//        boolean result =   modelInfoService.checkModelInfo(modelInfo);
//        if (!result){
//            throw new RuntimeException("模型名称已存在");
//        }

        int success = modelInfoService.updateModelInfo(modelInfo);
        if(success < 1){
            return error("保存失败！");
        }
        return toAjax(success);
    }

    /**
     * 删除模型信息
     */
    @RequiresPermissions("model:info:remove")
    @Log(title = "模型管理/模型信息", businessType = BusinessType.DELETE)
    @GetMapping("/del/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(modelInfoService.deleteModelInfoByIds(ids));
    }

}
